<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>WebSocket 登录示例</title>
    <!-- 引入 Element UI 样式 -->
    <link rel="stylesheet" href="./css/element-ui@2.15.14.css">
    <style>
        body {
            padding: 30px;
            font-family: Arial, sans-serif;
        }
        #log {
            white-space: pre-wrap;
            background-color: #f5f7fa;
            padding: 10px;
            margin-top: 20px;
            height: 300px;
            overflow-y: auto;
        }
    </style>
</head>
<body>
<div id="app">
    <p>用户名：{{ loginForm.username }}</p>
    <p>登录状态：{{ loginStatus }}</p>
    <p>Token：{{ token }}</p>
    <el-card style="width: 400px;">
        <h3>WebSocket 登录</h3>
        <div v-if="loginStatus === '未登录'">
            <el-form :model="loginForm" label-width="80px">
                <el-form-item label="用户名">
                    <el-input v-model="loginForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码">
                    <el-input type="password" v-model="loginForm.password" show-password></el-input>
                </el-form-item>
                <el-button type="primary" @click="login">登录</el-button>
            </el-form>
        </div>
        <div v-else>
            <el-form :inline="true" :model="senMsg" class="demo-form-inline">
                <el-form-item label="发给谁">
                    <el-select v-model="senMsg.toUser" placeholder="发给谁">
                        <el-option label="zhangsan" value="zs"></el-option>
                        <el-option label="lisi" value="ls"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="消息">
                    <el-input v-model="senMsg.message" placeholder="消息"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="sendMessage">发送</el-button>
                </el-form-item>
            </el-form>
        </div>
    </el-card>
    <div id="log">
        <strong>日志：</strong><br/>
        {{ socketLog }}
    </div>
</div>

<!-- 引入 Vue 和 Element UI -->
<script src="./js/vue@2.7.16.js"></script>
<script src="./js/element-ui@2.15.14.js"></script>
<script src="./js/messageType.js"></script>
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                socketUrl: 'ws://localhost:8848/ws',
                websocket: null,
                loginStatus: '未登录',
                token: '',
                socketLog: '',
                loginForm: {
                    username: 'ls',
                    password: '123'
                },
                reconnectTimer: null,
                reconnectAttempts: 0,
                maxReconnectAttempts: 3,
                senMsg: {
                    toUser: '',
                    message: ''
                }
            };
        },
        methods: {
            connect() {
                this.log("尝试连接 WebSocket...");

                this.websocket = new WebSocket(this.socketUrl);

                this.websocket.onopen = () => {
                    this.reconnectAttempts = 0; // 重置重试次数
                    this.log("WebSocket 已连接");

                    if (this.loginStatus !== '已登录') {
                        this.sendLogin(); // 如果未登录，发送登录信息
                    }
                };

                this.websocket.onmessage = (event) => {
                    try {
                        const message = JSON.parse(event.data);
                        this.handleMessage(message);
                    } catch (e) {
                        this.log(`非 JSON 消息: ${event.data}`);
                    }
                };

                this.websocket.onclose = () => {
                    this.log("WebSocket 已关闭");
                    this.loginStatus = '未登录';
                    this.token = '';
                    this.startReconnect();
                };

                this.websocket.onerror = (error) => {
                    this.log(`WebSocket 错误: ${error.message}`);
                    this.websocket.close();
                };
            },

            // startReconnect() {
            //     if (this.reconnectAttempts >= this.maxReconnectAttempts) {
            //         this.log("已达最大重试次数，停止重连");
            //         return;
            //     }
            //
            //     this.reconnectTimer = setTimeout(() => {
            //         this.reconnectAttempts++;
            //         this.log(`正在尝试第 ${this.reconnectAttempts} 次重连...`);
            //         this.connect();
            //     }, 5000);
            // },

            log(msg) {
                this.socketLog += `${new Date().toLocaleTimeString()} - ${msg}\n`;
            },

            login() {
                if (!this.loginForm.username || !this.loginForm.password) {
                    this.$message.error('请输入用户名和密码');
                    return;
                }

                this.connect();
            },

            sendLogin() {
                if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
                    this.log("WebSocket 未就绪，无法发送登录消息");
                    return;
                }

                this.websocket.send(JSON.stringify({
                    messageType: LOGIN_REQUEST,
                    userModel: {
                        username: this.loginForm.username,
                        password: this.loginForm.password
                    }
                }));
            },

            handleMessage(message) {
                if (!message.from){
                    message.from = '系统';
                }
                if (message.messageType === LOGIN_REQUEST) {
                    if (message.content === '登录成功') {
                        this.loginStatus = '已登录';
                        this.token = message.token || 'dummy_token';
                        this.log("登录成功");
                    } else {
                        this.loginStatus = '未登录';
                        this.token = '';
                        this.$message.error(message.content || '登录失败');
                    }
                } else if (message.messageType === MESSAGE_REQUEST) {
                    this.log(`收到${message.from}的聊天消息: ${message.content}`);
                } else if (message.messageType === ERROR_CODE) {
                    this.log("错误信息: " + message.content)
                    this.$message.error(message.content || '登录失败');
                }else {
                    this.log("未知消息类型: " + JSON.stringify(message));
                }
            },

            logout() {
                this.loginStatus = '未登录';
                this.token = '';
                this.websocket.close();
            },
            sendMessage(){
                if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
                    this.log("WebSocket 未就绪，无法发送消息");
                    return;
                }
                if (this.loginStatus !== '已登录') {
                    this.$message.error('请先登录');
                    return;
                }

                const message = this.senMsg.message;
                if (!message) {
                    this.$message.error('请输入消息内容');
                    return;
                }

                this.websocket.send(JSON.stringify({
                    messageType: MESSAGE_REQUEST,
                    to: this.senMsg.toUser,
                    content: message,
                    token: this.token
                }))
                this.log(`发送消息给${this.senMsg.toUser}: ${message}`);
                this.senMsg.message = '';
            }
        }
    });
</script>
</body>
</html>
